package com.lang.timetask;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.lang.beans.Courier;
import com.lang.beans.Parcel;
import com.lang.beans.Task;
import com.lang.service.CourierService;
import com.lang.service.ParcelService;
import com.lang.service.TaskService;
import com.lang.util.Config;

public class QuartzTask extends QuartzJobBean {

	private ParcelService parcelservice;
	private CourierService courierservice; // 邮差服务类，提供各种逻辑操作
	private TaskService taskservice;

	public static int allParcelsNum=0; // 当前包裹的派送总数
	public static int avagerNum=0; // 当前包裹的平均数
	private static Map couriers = new HashMap(); //

	public ParcelService getParcelservice() {
		return parcelservice;
	}

	public void setParcelservice(ParcelService parcelservice) {
		this.parcelservice = parcelservice;
	}

	public CourierService getCourierservice() {
		return courierservice;
	}

	public void setCourierservice(CourierService courierservice) {
		this.courierservice = courierservice;
	}

	public TaskService getTaskservice() {
		return taskservice;
	}

	public void setTaskservice(TaskService taskservice) {
		this.taskservice = taskservice;
	}

	// 进行公平分配任务
	@Override
    protected void executeInternal(JobExecutionContext arg0)
            throws JobExecutionException {
        System.out.println("20秒执行一次 公平分配");
        
        this.parcelservice=new ParcelService();
        this.courierservice=new CourierService();
        this.taskservice=new TaskService();
        
		//先获取未处理的包裹
		List parcels=this.parcelservice.getParcelsByStatus(Config.PAECEL_UNDEAL);
		
		System.out.println("undelingparcel"+parcels.size());
		
		if(parcels!=null){
			//再获取邮差
			
			System.out.println("包裹不为空");
			
			List couriers=this.courierservice.getCouriersByPermission(Config.COURIER);
			initMap(couriers);  //转化为Map全局变量，记录当天某个邮差的派送量();
			//记录到任务表
			if(couriers!=null){
				for (Iterator i = parcels.iterator(); i.hasNext();) {
					Parcel p=(Parcel)i.next();
					for (Iterator j = couriers.iterator(); j.hasNext();) {
						Courier c=(Courier)j.next();
						int n=(Integer)this.couriers.get(c.getId());  //获取到对应的邮差当天分派的任务数量
						if(n<=avagerNum){      //当不满足当天的派件收件平均数时，就分派任务
							taskservice.addTask(new Task(),p.getId());  //分别更新两个表
							this.couriers.put(c.getId(), n+1);
							break;   //限制一个包裹只能被分派一次
						}
					}
		            
		        }
			}
		}	
		System.out.println("执行完毕!!");
    }

	/**
	 * 将获取的邮差转化成 map
	 */
	public void initMap(List cs) {
		if (this.couriers.size() == 0) {
			if (cs != null) {
				for (Iterator i = cs.iterator(); i.hasNext();) {
					this.couriers.put(((Courier) i.next()).getId(), 0);
				}
			}
		}
	}
}
